package org.panxiong.openapi.mojo;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Arrays;

@Mojo(name = "test-plugin", defaultPhase = LifecyclePhase.PREPARE_PACKAGE)
public class TestPluginMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    private String appBasePackage;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
//        initBasePackage(new File(project.getBuild().getOutputDirectory()));
        getLog().info("插件运行成功 " + appBasePackage);
//        testClass();
    }

    private void initBasePackage(File file) {
        if (!file.isDirectory()) {
            return;
        }
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length <= 0) {
            appBasePackage = file.getAbsolutePath().replace(project.getBuild().getOutputDirectory() + File.separator, "");
        } else {
            boolean allMatchClass = Arrays.stream(listFiles).anyMatch(it -> it.getName().endsWith(".class"));
            if (!allMatchClass) {
                for (File listFile : listFiles) {
                    initBasePackage(listFile);
                }
            } else {
                appBasePackage = file.getAbsolutePath().replace(project.getBuild().getOutputDirectory() + File.separator, "");
            }
        }
        appBasePackage = appBasePackage.replace(File.separator, ".").trim();
    }

    private void testClass() {
        try {
            // 指定类文件的路径
            String classPath = project.getBuild().getOutputDirectory() + "\\org\\panxiong\\test\\controller\\HelloController.class";
            getLog().info("文件1：" + classPath);
            // 获取类的目录
            File file = new File(classPath);
            String directoryPath = file.getParentFile().toURI().toURL().toString();
            // 加载类
//            URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL(directoryPath)});
            String u = "file:///" + project.getBuild().getOutputDirectory().replace("\\", "/");
            String path = Paths.get(project.getBuild().getOutputDirectory()).toUri().toURL().getPath();
            getLog().info("文件2：" + u + " " + path);
            URL url = Paths.get(project.getBuild().getOutputDirectory()).toUri().toURL();
//            URL url = Paths.get("target/classes/").toUri().toURL();

            URLClassLoader classLoader = new URLClassLoader(new URL[]{url}, this.getClass().getClassLoader());
            // 获取类名（不包括路径和扩展名）
            String className = file.getName().replace(".class", "");
            // 加载类
            getLog().info("文件3：" + url);
//            Class<?> clazz = classLoader.loadClass(className);
            Class<?> clazz = classLoader.loadClass("org.panxiong.test.controller.HelloController");

            // 获取并打印方法列表
            Method[] methods = clazz.getDeclaredMethods();
            RestController restController = clazz.getAnnotation(RestController.class);
            getLog().info("Methods in class " + className + " : " + restController);
            for (Method method : methods) {
                getLog().info("123 " + method.getName());

                getLog().info("456 " + method.getAnnotation(GetMapping.class));
                getLog().info("789 " + method.getAnnotations().length);

                for (Annotation annotation : method.getAnnotations()) {
                    getLog().info("aaa " + annotation.getClass().getName());
                }
            }
            // 关闭类加载器
            classLoader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
